package cn.laixueit.controller;

import cn.hutool.core.io.FileUtil;
import cn.laixueit.base.CommonEnum;
import cn.laixueit.base.R;
import cn.laixueit.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author duxiang
 * @date 2023/12/25 16:24
 */
@RestController
@RequestMapping("/file")
public class FileUplodaController {

    @Resource
    private CommonUtils commonUtils;
    @Value("${file.path}")
    private String filePath;
    @Value("${file.url}")
    private String fileUrl;

    @PostMapping("/upload")
    public R upload(@RequestParam(name = "dir",required = false)String dirName,@RequestParam("file") MultipartFile... multipartFile){
        Map<String, String> map = new HashMap<>();
        try {
            for (MultipartFile file : multipartFile) {
                // 创建文件夹
                Map<String, Object> mkdirMap = commonUtils.createMkdir(dirName, filePath);
                String originalFilename = file.getOriginalFilename();
                File mkdir = (File) mkdirMap.get("file");
                String dir = (String) mkdirMap.get("dir");
                String randomName = commonUtils.randomName(originalFilename);
                File newFile = new File(mkdir.getAbsolutePath(), randomName);
                file.transferTo(newFile);
                map.put(originalFilename,fileUrl+dir+"/"+randomName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        }
        return R.ok().put("originNames",map);
    }
}
